package com.abvnet.project.water.api.web;

import com.abvnet.common.utils.StringUtils;
import com.abvnet.common.utils.file.FileUtils;
import com.abvnet.framework.config.AbvnetConfig;
import com.abvnet.framework.web.controller.BaseController;
import com.abvnet.framework.web.domain.AjaxResult;
import com.abvnet.project.water.project.service.IProjectContractService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

@Controller
@RequestMapping("/api/contract")
@Slf4j
public class ApiProjectContractController extends BaseController {

    @Autowired
    private IProjectContractService projectContractService;

    @GetMapping("/get")
    @ResponseBody
    public AjaxResult get(@RequestParam("projectId") Long projectId) {
        return AjaxResult.success(projectContractService.selectProjectContractByProjectId(projectId));
    }

    @GetMapping("/download")
    public void fileDownload(String url, HttpServletResponse response, HttpServletRequest request) {
        String fileName = StringUtils.substringAfterLast(url, "/");
        String filePath = AbvnetConfig.getContractPath() + url;
        File file = new File(filePath);
        try {
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            long total = file.length();
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition","attachment;fileName=" + fileName);
            response.setHeader("Content-Range","bytes 0-"+(total-1)+"/"+total);
            response.setHeader("Content-Length",String.valueOf(total));
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (IOException e) {
            log.error("download contract [{}]", e.toString());
        }
    }
}